/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.client.loader;

import io.iec.edp.caf.commons.core.SerializerFactory;
import io.iec.edp.caf.commons.core.enums.SerializeType;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.api.annotation.GspServiceBundle;
import io.iec.edp.caf.rpc.api.entity.RpcServiceDefinition;
import io.iec.edp.caf.rpc.api.local.InternalServiceLocalStorage;

import io.iec.edp.caf.rpc.api.utils.DefinitionUtil;

import io.iec.edp.caf.rpc.registry.api.RpcDefinitionRegistry;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Rpc服务注册到Rpc服务注册中心
 *
 * @author guowenchang
 */

@Slf4j
public class RpcServiceRegistryStarter {

    //todo 对自定义序列化参数支持不好
    public static void registerRpcService(Set<Class<?>> rpcInterfaces) {
        long startTime = System.currentTimeMillis();
        List<RpcServiceDefinition> definitionList = new ArrayList<>();
        for (Class<?> c : rpcInterfaces) {
            if (c.getDeclaredAnnotation(GspServiceBundle.class) == null) {
                log.warn("interface " + c.getName() + " not use GspServiceBundle annotation.");
                continue;
            }

            try {
                RpcServiceDefinition rpcServiceDefinition = DefinitionUtil.transformServiceDefinition(c);
                definitionList.add(rpcServiceDefinition);

            } catch (Exception e) {
                log.error("scan RPC Interface: " + c.getName() + " error, caused by: " + e.getMessage());
            }
        }

        //操作底座的RpcDefinitionRegistry
        RpcDefinitionRegistry rpcDefinitionRegistry = SpringBeanUtils.getBean(RpcDefinitionRegistry.class);

        if (rpcDefinitionRegistry == null) {
            log.error("Bean RpcClientServiceRegistry not found");
            return;
        }

        //rpc definition存储到本地
        if(log.isInfoEnabled()){
            log.info("current server all rpc service: {}",SerializerFactory.getSerializer(SerializeType.Json).serializeToString(definitionList));
        }
        InternalServiceLocalStorage.current.setRpcServiceDefinitions(definitionList);
        //rpc definition注册到Rpc服务中心
        rpcDefinitionRegistry.register(definitionList);
        long endTime = System.currentTimeMillis();
        log.info("iGIX register rpc service tools: {} ms",endTime - startTime);
    }
}
